package com.xiaowu.netmusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowu.netmusic.domain.po.Favorite;
import com.xiaowu.netmusic.domain.vo.SongVO;
import com.xiaowu.netmusic.mapper.FavoriteMapper;
import com.xiaowu.netmusic.service.FavoriteService;
import com.xiaowu.netmusic.service.SongService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    private final SongService songService;

    @Override
    public boolean addFavorite(Long userId, Long songId) {
        // 如果已存在则不重复添加
        /*
            QueryWrapper<Favorite>：MyBatis-Plus 的条件构造器，用于生成 SQL 查询条件。
            eq("user_id", userId)：表示添加 SQL 条件 user_id = userId。
            eq("song_id", songId)：添加 SQL 条件 song_id = songId。
            总的查询语句大概是：SELECT * FROM favorite WHERE user_id = ? AND song_id = ?
          */
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("song_id", songId);
        if (this.getOne(wrapper) != null) {
            return true;
        }
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setSongId(songId);
        return this.save(favorite);
    }

    @Override
    public boolean removeFavorite(Long userId, Long songId) {
        return this.remove(new QueryWrapper<Favorite>().eq("user_id", userId).eq("song_id", songId));
    }

    @Override
    public List<SongVO> getFavoriteSongs(Long userId) {
        List<Favorite> favorites = this.list(new QueryWrapper<Favorite>().eq("user_id", userId));
        return favorites.stream()
                .map(f -> songService.getById(f.getSongId()))
                .filter(Objects::nonNull)
                .map(song -> {
                    SongVO vo = new SongVO();
                    BeanUtils.copyProperties(song, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public boolean isFavorite(Long userId, Long songId) {
        return this.count(new QueryWrapper<Favorite>().eq("user_id", userId).eq("song_id", songId)) > 0;
    }
}
